package org.example.controller.enterprise;

import cn.dev33.satoken.annotation.SaCheckLogin;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.common.result.Result;
import org.example.common.utils.SaTokenUtils;
import org.example.common.utils.TenantContext;
import org.example.service.AuthService;
import org.example.service.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 企业端认证控制器
 */
@RestController
@RequestMapping("/enterprise/auth")
@Slf4j
@Component("enterpriseAuthController")
@Tag(name = "企业端-认证", description = "企业端认证相关接口，支持多租户")
@SecurityRequirement(name = "enterpriseBearerAuth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private SaTokenUtils saTokenUtils;

    @Autowired
    private CompanyService companyService;

    /**
     * 企业端登录接口
     * 路径：/api/enterprise/auth/login
     */
    @PostMapping("/login")
    @Operation(
        summary = "企业端-用户登录",
        description = "企业端用户通过手机号+验证码登录，支持多租户"
    )
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> loginRequest) {
        try {
            String phone = loginRequest.get("phone");
            String verificationCode = loginRequest.get("verificationCode");
            String companyId = loginRequest.get("companyId"); // 可选：指定登录的租户
            
            // 验证参数
            if (phone == null || verificationCode == null) {
                return Result.badRequest("手机号和验证码不能为空");
            }
            
            // 调用认证服务
            Map<String, Object> loginResult = authService.enterpriseLogin(phone, verificationCode, companyId);
            
            return Result.success("登录成功", loginResult);
            
        } catch (Exception e) {
            log.error("企业端登录失败", e);
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 切换租户
     */
    @PostMapping("/switch-tenant")
    @io.swagger.v3.oas.annotations.Operation(
        summary = "企业端-切换租户",
        description = "企业端用户切换到其他租户（企业）"
    )
    @SecurityRequirement(name = "enterpriseBearerAuth")
    @SaCheckLogin
    public Result<Map<String, Object>> switchTenant(@RequestBody Map<String, String> request) {
        try {
            String companyId = request.get("companyId");
            
            if (companyId == null) {
                return Result.badRequest("租户ID不能为空");
            }
            
            // 使用Sis_topa-Token获取当前用户信息
            Long userId = saTokenUtils.getCurrentUserId();
            String token = saTokenUtils.getTokenValue();
            
            Map<String, Object> newLoginInfo = authService.switchTenant(token, Long.valueOf(companyId));
            return Result.success("租户切换成功", newLoginInfo);
            
        } catch (Exception e) {
            log.error("企业端租户切换失败", e);
            return Result.error("租户切换失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户可用的租户列表
     */
    @PostMapping("/available-tenants")
    @io.swagger.v3.oas.annotations.Operation(
        summary = "企业端-获取可用租户",
        description = "获取当前用户可访问的企业租户列表"
    )
    @SecurityRequirement(name = "enterpriseBearerAuth")
    @SaCheckLogin
    public Result<Map<String, Object>> getAvailableTenants() {
        try {
            // 使用Sa-Token获取当前用户信息
            Long userId = saTokenUtils.getCurrentUserId();
            // 从租户上下文获取companyId（多端隔离）
        Long companyId = TenantContext.getCurrentCompanyId();

            // 调用公司服务返回可用租户
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            java.util.List<Map<String, Object>> availableTenants = companyService.getAvailableTenants(userId, companyId);
            
            // 为每个租户添加 is_current 标记
            for (Map<String, Object> tenant : availableTenants) {
                Object tenantId = tenant.get("companyId");
                tenant.put("is_current", tenantId != null && tenantId.equals(companyId));
            }
            
            result.put("currentTenant", companyId);
            result.put("availableTenants", availableTenants);

            return Result.success("获取租户列表成功", result);
            
        } catch (Exception e) {
            log.error("企业端获取租户列表失败", e);
            return Result.error("获取租户列表失败：" + e.getMessage());
        }
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    @io.swagger.v3.oas.annotations.Operation(
        summary = "企业端-退出登录",
        description = "企业端用户退出登录"
    )
    public Result<String> logout(@RequestBody Map<String, String> request) {
        try {
            try {
                Long userId = saTokenUtils.getCurrentUserId();
                String sessionId = saTokenUtils.getSessionId();
                org.example.service.LoginLogService loginLogService = org.springframework.web.context.ContextLoader.getCurrentWebApplicationContext().getBean(org.example.service.LoginLogService.class);
                if (userId != null && sessionId != null) {
                    loginLogService.recordLogout(userId, sessionId);
                }
            } catch (Exception ignore) {}
            saTokenUtils.logout();
            return Result.success("退出登录成功");
        } catch (Exception e) {
            log.error("退出登录失败", e);
            return Result.error("退出登录失败：" + e.getMessage());
        }
    }
}
